from odoo import models, fields, api, _
from odoo.exceptions import ValidationError


class StudentRoomAssignmentWizard(models.TransientModel):
    _name = 'student.room.assignment.wizard'
    _description = 'Student Room Assignment Wizard'

    student_id = fields.Many2one('hostel.student', string="Student", required=True,
                                help="Select the student to assign to a room")
    room_id = fields.Many2one('hostel.room', string="Room", required=True,
                             help="Select the room to assign the student to")
    hostel_id = fields.Many2one('hostel.hostel', string="Hostel", 
                               related='room_id.hostel_id', readonly=True,
                               help="Hostel of the selected room")
    current_room = fields.Char(string="Current Room", 
                               related='student_id.room_id.name', readonly=True,
                               help="Student's current room")
    room_availability = fields.Integer(string="Room Availability", 
                                       related='room_id.availability', readonly=True,
                                       help="Available beds in the selected room")
    assignment_date = fields.Date(string="Assignment Date", 
                                 default=fields.Date.context_today, required=True,
                                 help="Date when the assignment takes effect")

    @api.onchange('room_id')
    def _onchange_room_id(self):
        """当选择房间时更新相关信息"""
        if self.room_id:
            self.hostel_id = self.room_id.hostel_id
            self.room_availability = self.room_id.availability

    def action_assign_student_to_room(self):
        """分配学生到房间"""
        if not self.student_id or not self.room_id:
            raise ValidationError(_('Please select both student and room'))
        
        # 检查房间可用性
        if self.room_id.availability <= 0:
            raise ValidationError(_('Selected room has no available beds'))
        
        # 检查学生是否已在同一房间
        if self.student_id.room_id == self.room_id:
            raise ValidationError(_('Student is already assigned to this room'))
        
        # 使用sudo()绕过权限检查
        self.student_id.sudo().room_id = self.room_id.id
        
        # 更新学生的入住日期
        if self.assignment_date:
            self.student_id.sudo().check_in_date = self.assignment_date
        
        return {
            'type': 'ir.actions.client',
            'tag': 'reload',
        }

    def action_remove_student_from_room(self):
        """从房间移除学生"""
        if not self.student_id:
            raise ValidationError(_('Please select a student'))
        
        if not self.student_id.room_id:
            raise ValidationError(_('Student is not assigned to any room'))
        
        # 使用sudo()绕过权限检查
        self.student_id.sudo().room_id = False
        
        return {
            'type': 'ir.actions.client',
            'tag': 'reload',
        }
